<template>
  <view class="animated fadeIn faster page-bg">
    <view class="position-fixed top-0 right-0 left-0  z-index-100">
      <view class="d-flex d-flex-center d-flex-middle"
            :style="{'height': titleBarHeight + 'px','paddingTop':statusBarHeight+'px'}">
      </view>

      <view class="custom-nav-bar">
        <view class="back-btn" @click="handleBack">
          <text class="iconfont icon-a-jiantouyouxiao  font50"></text>
        </view>
      </view>

    </view>

    <view class="bg" :style="{backgroundImage: 'url(' + avatar + ')'}">
      <view class="head ">
        <image class="img"
               :src="avatar"/>
      </view>
    </view>
    <view class="mt-7 pt-5 px-2 text-center font36 font-bold"> {{ name }}
      <text class="iconfont icon-nansheng"
            style="color: #1296db;"></text>
    </view>
    <!--		<view class="d-flex d-flex-around mx-5 px-2 mt-2">-->
    <!--			<view>粉丝数：<text>10</text></view>-->
    <!--			<text class="bgcolor598dfc px-1 rounded30 colorfff font24 mr-5">关注</text>-->
    <!--			<view class="ml-4">-->
    <!--				<image style="width: 40rpx; display: inline-block;" mode="widthFix"-->
    <!--					src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/love.png" />-->
    <!--				<text class="ml-1">lv.1</text>-->
    <!--			</view>-->
    <!--			<view>-->
    <!--				<image style="width: 40rpx; display: inline-block;" mode="widthFix"-->
    <!--					src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/diamond.png" />-->
    <!--				<text class="ml-1">lv.1</text>-->
    <!--			</view>-->
    <!--		</view>-->
    <view class="text-clamp-two font28 my-1 color999 px-2 my-2 text-center">
      {{ characters_introduce }}
    </view>

    <view class="m-2 px-2 py-1 d-flex grabClass rounded10 bg-fff d-flex-between">
      <text>陪练品类</text>
      <text class="iconfont icon-xiajiantou color999"></text>
    </view>


    <view class="mx-2 my-2">
      <scroll-view
          style="height: calc(100vh - 690rpx);"
          scroll-y
          refresher-enabled
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh">
        <view v-for="(item,inde) in list" :key="inde+'c'"
              class="py-2 px-1 bg-fff rounded20 mb-2 d-flex  d-flex-between">
          <view class="videoBtnView px-0-5" style="width: 30%;">
            <image :src="item.avatar" class="avatar"></image>
            <view v-if="item.voice_introduce"
                  class="voice-btn d-flex d-flex-middle d-flex-center px-3 py-1 rounded20 font22 "
                  @click="placeOrder(item,inde)">
              <text class="saying mr-1 font28 colorfff"
                    :class="videoIndex == inde?'iconfont icon-saying':'iconfont icon-Gc_10_face-PlayCircle'"></text>
            </view>
          </view>
          <view class="d-flex d-flex-item d-flex-column d-flex-between"
                @click="goUrl(`/subPages/orderAlone/orderAlone?data=${encodeURIComponent(JSON.stringify(item))}`)"
          >
            <view class="font-bold font30  d-flex  d-flex-between d-flex-middle">
                <text class="text-clamp"  style="width: 260rpx">{{ item.name }}</text>
                <text :title="item.unions_name" class="colorff7f02 font26 font-400 text-clamp" style="width: 180rpx">{{ item.unions_name }}</text>
            </view>
            <view class="d-flex font24 d-flex-between" >
              <text>游戏名称：</text>
              <text class="main-color">{{item.game_name}}</text>
            </view>
            <view style="height: 66rpx" class=" text-clamp-two font26 my-1 color333">{{ item.remark }}
            </view>
            <view class="d-flex d-flex-middle d-flex-between">
              <view class="d-flex d-flex-column font26">
                <view>
                  <text class="colorf00 font36 font-bold ml-1-5">{{ item.skill_price }}</text>
                  <text class="color999 font22 "> 元/小时</text>
                </view>
              </view>
              <view class="bgcolor598dfc px-3 py-1 rounded30 colorfff font22"
              >下单
              </view>
            </view>

          </view>
        </view>
      </scroll-view>
    </view>


  </view>
</template>

<script>
import {
  mapState
} from "vuex"
import {homeApi} from "@/http/homeApi";

export default {
  data() {
    return {
      list: [],
      name: '',
      avatar: '',
      characters_introduce: '',
      // 添加音频上下文引用
      currentAudioContext: null,
      refreshing: false,
      loadingMore: false,
      noMoreData: false,
      page: 1,
      userId:'',
      videoIndex: -1,
    }
  },
  onLoad(data) {
    let option = JSON.parse(decodeURIComponent(data.data))
    this.name = option.name
    this.avatar = option.avatar;
    this.characters_introduce = option.characters_introduce
    this.userId = option.user_id
    this.initInfo(option.user_id)
  },
  computed: {
    ...mapState({
      loginState: state => state.loginState,
      statusBarHeight: state => state.statusBarHeight,
      titleBarHeight: state => state.titleBarHeight,
    })
  },
  methods: {
    async initInfo(id, isLoadMore = false) {
      // 如果不是加载更多，则重置分页信息
      if (!isLoadMore) {
        this.page = 1
        this.noMoreData = false
      }
      try {
        let res = await homeApi.getPlaySkill(id)
        if (isLoadMore) {
          // 加载更多数据
          if (res.data && res.data.length > 0) {
            this.list = this.list.concat(res.data)
            this.page++
          } else {
            this.noMoreData = true
          }
        } else {
          // 刷新数据
          this.list = res.data || []
          this.page = 2
          if (!res.data || res.data.length < this.pageSize) {
            this.noMoreData = true
          }
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        })
      }
    },
    async onRefresh() {
      this.refreshing = true;
      try {
        // 重新获取数据
        await this.initInfo(this.userId);
      } finally {
        this.refreshing = false;
      }
    },
    goUrl(urlPages) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
    handleBack() {
      uni.navigateBack({
        delta: 1,
      })
    },
    placeOrder(data, index) {
      // 如果点击的是同一个正在播放的项目，则停止播放
      if (this.videoIndex === index) {
        this.stopVoiceIntroduction();
        return;
      }

      this.videoIndex = index;

      // 播放语音介绍
      this.playVoiceIntroduction(data.voice_introduce);
    },

    // 播放语音介绍
    playVoiceIntroduction(voiceUrl) {
      if (!voiceUrl) {
        uni.showToast({
          title: '暂无语音介绍',
          icon: 'none'
        });
        this.videoIndex = -1;
        return;
      }

      // 如果有正在播放的音频，先停止
      if (this.currentAudioContext) {
        this.currentAudioContext.destroy();
      }

      // 创建音频上下文
      this.currentAudioContext = uni.createInnerAudioContext();

      // 设置音频地址
      this.currentAudioContext.src = voiceUrl;

      // 监听播放事件
      this.currentAudioContext.onPlay(() => {
        console.log('开始播放语音介绍');
      });

      // 监听播放结束事件
      this.currentAudioContext.onEnded(() => {
        console.log('语音介绍播放结束');
        this.resetVoiceState();
      });

      // 监听播放错误事件
      this.currentAudioContext.onError((res) => {
        console.error('语音播放失败', res);
        uni.showToast({
          title: '语音播放失败',
          icon: 'none'
        });
        this.resetVoiceState();
      });

      // 开始播放
      this.currentAudioContext.play();
    },

    // 停止播放语音介绍
    stopVoiceIntroduction() {
      if (this.currentAudioContext) {
        this.currentAudioContext.stop();
        this.currentAudioContext.destroy();
        this.currentAudioContext = null;
      }
      this.resetVoiceState();
    },

    // 重置语音播放状态
    resetVoiceState() {
      this.videoIndex = -1;
    },

  },
  beforeDestroy() {
    // 页面销毁时停止并清理音频资源
    if (this.currentAudioContext) {
      this.currentAudioContext.stop();
      this.currentAudioContext.destroy();
      this.currentAudioContext = null;
    }
  },
}
</script>


<style scoped>
.bg {
  width: 100%;
  height: 360rpx;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  position: relative;
}

.head {
  width: 190rpx;
  height: 190rpx;
  position: absolute;
  bottom: -30%;
  left: 36%;
  border: 20rpx solid rgba(255, 255, 255, .3);
  border-radius: 50%;
  overflow: hidden;
}

.head .img {
  height: 100%;
  width: 100%;
}

.bgcolor598dfc {
  background-color: #598dfc;
}

.px-0-5 {
  padding-left: 6rpx;
  padding-right: 20rpx;
}

.colorff7f02 {
  color: #ff7f02;
}

.grabClass {
  overflow: hidden;
}

.grabClass view:nth-child(1),
.grabClass view:nth-child(2) {
  border-right: 2rpx solid #f4f6fa;
}

.grabClassActive {
  background-color: #f4f6fa;
}


.videoBtnView {
  position: relative;
}

.videoBtnView .avatar {
  width: 206rpx;
  height: 206rpx;
  background: #f6f6f6;
  overflow: hidden;
}

.voice-btn {
  position: absolute;
  bottom: -10rpx;
  left: 0;
  background: linear-gradient(135deg, #a6c0fe, #f68084);
  border: none;
  color: #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(74, 105, 189, 0.3);
  transition: all 0.3s ease;
  border-radius: 20rpx;
  padding: 10rpx 15rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.voice-btn:hover {
  background: linear-gradient(135deg, #a6c0fe, #f68084);
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 16rpx rgba(74, 105, 189, 0.4);
}

/* 录音中状态 */
.voice-btn-recording {
  background: linear-gradient(135deg, #e55039, #eb2f06);
  animation: pulse 1.5s infinite;
}


@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10rpx rgba(255, 107, 107, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0);
  }
}

.saying {
  font-size: 28rpx;
}

.icon-Gc_10_face-PlayCircle {
  font-size: 28rpx;
}

.icon-saying {
  animation: voiceAnimate 1s infinite;
}

@keyframes voiceAnimate {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

.mr-1 {
  margin-right: 10rpx;
}


.saying {
}

.mr-1 {
  margin-right: 10rpx;
}

.custom-nav-bar {
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.back-btn {
  display: flex;
  align-items: center;
  padding: 5px 0;
}
</style>